<?php
/**
 * @Author: rocky
 * @Copyright: 广州拓冠科技 <http://my8m.com>
 * Date: 2019/7/11
 * Time: 15:48
 */


namespace app\common\tools;


use app\common\service\ApiCode;
use think\exception\HttpResponseException;


trait  ApiJson
{
    /**
     * 返回成功json
     * @Author: rocky
     * 2019/7/11 16:02
     * @param $code
     * @param $data 输出数据
     * @return \think\response\Json
     */
    public function successCode($data = [],$code=200)
    {
        $response =  $this->responseJsonData($data, $code);
        throw new HttpResponseException($response);
    }

    /**
     * 返回失败json
     * @Author: rocky
     * 2019/7/11 16:02
     * @param $code
     * @param $msg
     * @return \think\response\Json
     */
    public function errorCode($code = 100, $msg = '')
    {
        $response =  $this->responseJsonData([], $code, $msg);
        throw new HttpResponseException($response);
    }

    /**
     * 输出自定义json
     * @Author: rocky
     * 2019/7/12 17:08
     * @param array $data 数据
     * @param int $code 错误码
     * @param string $errMsg 错误信息
     * @param int $http_code 状态码
     */
    protected function responseJsonData($data = [], $code = 100, $errMsg = '', $http_code = 200)
    {
        $return['code'] = (int)$code;
        if (!empty($errMsg)) {
            $return['msg'] = $errMsg;
        } else {
            $return['msg'] = ApiCode::$code[$code];
        }
        $return['data'] = $data;

        return json($return, $http_code);
    }
}